package com.logistics.utils.tool;

import com.logistics.utils.bean.UserBean;
import com.logistics.utils.jwt.JwtRegistry;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class UserUtils {

    @Autowired
    private JwtRegistry jwtRegistry;

    /**
     * 获取用户ID
     * @return
     */
    public String getUserId(){
        return getUserInfo().getUserId();
    }

    public UserBean getUserInfo(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = StringUtils.isNotNull(request.getHeader("token")) ? request.getHeader("token")
                : request.getParameter("token");
        if(StringUtils.isNull(token)){
            return null;
        }
        Claims Claims = jwtRegistry.parseJWT(token);
        String subject = Claims.getSubject();
        return StringUtils.stringToBena(subject, UserBean.class);
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    public UserBean getUserInfo(String token){
        Claims Claims = jwtRegistry.parseJWT(token);
        String subject = Claims.getSubject();
        return StringUtils.stringToBena(subject, UserBean.class);
    }

}
